<?php
//
// THE DAILY PEN FUNCTIONS
// By Christian Touzel
//


// GET RANDOM ITEM FROM XML
function GetRandomItemFromXML($customXML)
{
	$retval = "";
	$xmlcustom=($customXML);
	$xmlcustomDoc = new DOMDocument();
	$xmlcustomDoc->load($xmlcustom);
	$x=$xmlcustomDoc->getElementsByTagName('item');
	$xlen=$xmlcustomDoc->getElementsByTagName('item')->length;
	$retval = $retval . $x->item(rand(0, $xlen-1))->nodeValue;
	return $retval;
}

// GET RANDOM QUOTE
function GetRandomQuote()
{
	$retval = "";
    try
    {
        $filename = "quotes.xml";

        if (file_exists($filename))
        {
            $xmlquotes = ("quotes.xml");
            $xmlquotesDoc = new DOMDocument();
            $xmlquotesDoc->load($xmlquotes);
            $x = $xmlquotesDoc->getElementsByTagName('quote');
            $xlen = $xmlquotesDoc->getElementsByTagName('quote')->length;
            $quote = $x->item(rand(0, $xlen - 1));
            $retval = $retval . "<i>" . $quote->nodeValue . "</i>";
            $retval = $retval . "<br>-" . $quote->getAttribute('source');
        }
        else
        {
            throw new Exception('Unable to find quotes.xml file');
        }
    }
    catch (Exception $e)
    {
        $lognow = new DateTime();
        $lognow->setTimezone(new DateTimeZone('America/Montreal'));
        $GLOBALS['errors'] = $GLOBALS['errors'] . "<p>".$lognow->format('H:i:s')."
            - ERROR - Unable to get random quote (".$e->getMessage().")</p>";
    }
	return $retval;
}


// READ WEATHER
function GetWeather($current)
{
	$retval = "<section><p>";
	$quick = 0;
    try {
        $currentweather = "";
        $feed = new SimplePie();
        $feed->set_feed_url("http://meteo.gc.ca/rss/city/qc-133_f.xml");
        $feed->handle_content_type();
        $feed->set_timeout(20);
        $feed->enable_order_by_date(false);
        $feed->set_cache_location($_SERVER['DOCUMENT_ROOT'] . '/cache');
        $feed->init();

        for ($i = 1; $i < 6; $i++) {
            $titleraw = $feed->get_item($i)->get_title();
            if (stripos($titleraw, "Conditions actuelles") !== false) {
                $subtitle = str_replace("Conditions actuelles:", "", $titleraw);
                if (strrpos($feed->get_item(0)->get_title(), "Aucune") === false) {
                    //$retval = "<h3>" . $subtitle . " / " . $feed->get_item(0)->get_title() . "</h3>";
                } else {
                    //$retval = "<h3>" . $subtitle . "</h3>";
                }
                $currentweather = $subtitle;
            } else {
				if ($quick == 1 || $quick == 2 || $quick == 3)
				{
					$sub = $feed->get_item($i)->get_title();
					$pos = stripos($sub, ":");
					$sub = substr($sub, 0, $pos);
					$retval = $retval . "<h3>" . $sub . "</h3>";
				}
                
            }
            $descraw = $feed->get_item($i)->get_description();
            if (stripos($descraw, "Humidit&eacute;") !== false) {
                $descraw = substr($descraw, stripos($descraw, "Humidit&eacute;"));
                $descraw = substr($descraw, 0, stripos($descraw, "Cote"));
                $descraw = str_replace("<b>", "", $descraw);
                $descraw = str_replace("<br>", ", ", $descraw);
            }

            $finalstr = $descraw;
			if ($quick == 1 || $quick == 2 || $quick == 3)
			{
				if (stripos($descraw, "Pr&eacute;visions") === false) {
					$retval = $retval . $descraw;
				} else {
					$pos = stripos($descraw, "Pr&eacute;visions");
					$desc = substr($descraw, 0, $pos);
					$retval = $retval . $desc;
				}
			}


            if (stripos($finalstr, "Point de") !== false) {
                //$retval = $retval . $descraw;
            }
			$quick = $quick + 1;
        }
        if ($current)
        {
            $retval = "<section><p><h3>".$currentweather."</h3>\r\n";
        }
    }
    catch (Exception $e)
    {
        $lognow = new DateTime();
        $lognow->setTimezone(new DateTimeZone('America/Montreal'));
        $GLOBALS['errors'] = $GLOBALS['errors'] . "<p>".$lognow->format('H:i:s')."
            - ERROR - Unable to retrieve weather (".$e->getMessage().")</p>";
    }
	$retval = $retval."</p></section>";
	return $retval;
}

// SEND EMAIL
function SendEmail($emailcontent, $emailEnabled)
{
	$now = new DateTime();
	$now->setTimezone(new DateTimeZone('America/Montreal'));
	$date_title = $now->format('F j, Y');
	$mail = new PHPMailer();
	$mail->CharSet = "UTF-8";
	$mail->IsSMTP();
	$mail->SMTPDebug  = 0;
	$mail->SMTPAuth   = true;
	$mail->SMTPSecure = "ssl";
	$mail->Host       = "smtp.gmail.com";
	$mail->Port       = 465;
	$mail->Username   = "larryzona966@gmail.com";
	$mail->Password   = "cactus1976";
	$mail->SetFrom('larryzona966@gmail.com');
	$mail->FromName = "Larry Zona";
	$mail->Subject    = $date_title;
	$mail->MsgHTML($emailcontent);
	$mail->AddAddress("readlater.okt7d91epek@instapaper.com", "");
	if ($emailEnabled)
	{
		if(!$mail->Send()) 
		{
			echo "<h3>Cannot send email. Problems encountered...</h3>";
		} 
		else 
		{
			echo "<h3>Message sent!</h3>";
		}
	}
	else
	{
		echo "<h3>Email Sending Disabled</h3>";
	}
}


// GET TODOIST TASKS
function GetTodoistTasks()
{
	$retval = "";
	try
	{
		date_default_timezone_set('America/Montreal');
		ini_set('memory_limit', '-1');
		set_time_limit(0);
		error_reporting(-1);

		$feed = curl_init();
		curl_setopt($feed, CURLOPT_URL, "http://www.todoist.com/API/getProjects?token=a3b4994d3e4525f8e559a8428e2872a90acf4dad");
		curl_setopt($feed, CURLOPT_HEADER, 0);
		curl_setopt($feed, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($feed, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($feed, CURLOPT_MAXREDIRS, 3);
		$projects_all = curl_exec($feed);
		curl_close($feed);
		$todoist_projects = json_decode($projects_all, true);

		$today = new DateTime();
		$today->setTimezone(new DateTimeZone('America/Montreal'));
		$today->setTime( 0, 0, 0 );
		$str_yesterday = "";
		$str_today = "";
		$str_tomorrow = "";

		foreach ($todoist_projects as $project)
		{
			$project_id = $project["id"];
			$feedItems = curl_init();
			curl_setopt($feedItems, CURLOPT_URL, "http://www.todoist.com/API/getUncompletedItems?token=a3b4994d3e4525f8e559a8428e2872a90acf4dad&project_id=".$project_id);
			curl_setopt($feedItems, CURLOPT_HEADER, 0);
			curl_setopt($feedItems, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($feedItems, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($feedItems, CURLOPT_MAXREDIRS, 3);
			curl_setopt($feedItems, CURLOPT_CONNECTTIMEOUT ,0); 
			curl_setopt($feedItems, CURLOPT_TIMEOUT, 400);
			$items_all = curl_exec($feedItems);
			curl_close($feedItems);	
			$todoist_data = json_decode($items_all, true);
			foreach ($todoist_data as $todo_item)
			{
				if (is_null($todo_item["due_date"])==false)
				{
					$time = new DateTime($todo_item["due_date"]);
					$time->setTimezone(new DateTimeZone('America/Montreal'));
					$time->setTime( 0, 0, 0 ); 
					$since_start = floor(($time->format('U') - $today->format('U')) / (60*60*24));
					switch( $since_start ) {
						case 0:
							$str_today = $str_today . "<li>" . $todo_item["content"]."</li>";
							break;
						case -1:
							$str_yesterday = $str_yesterday . "<li>". $todo_item["content"]."</li>";
							break;
						case +1:
							$str_tomorrow = $str_tomorrow . "<li>". $todo_item["content"]."</li>";
							break;
					}
				}
			}
		}
		if ($str_yesterday!="")
		{
			$retval = $retval. "<h3>Yesterday's Tasks</h3>";
			$retval = $retval.  "<ul>".$str_yesterday."</ul>";
		}
		$retval = $retval.  "<h3>Today's Tasks</h3>";
		$retval = $retval.  "<ul>".$str_today."</ul>";
	}
	catch (Exception $e) 
	{
		$lognow = new DateTime();
		$lognow->setTimezone(new DateTimeZone('America/Montreal'));
		$GLOBALS['errors'] = $GLOBALS['errors'] . "<p>".$lognow->format('H:i:s')." - ERROR - Unable to retrieve Todoist tasks (".$e->getMessage().")</p>";
	}
	return $retval;
}

// GET MLB STANDINGS
function GetMLBStandings()
{
	$standings = Array();
	$imgcount = 1;

	$liney = 20;
	$lines = array();
		
	$retval = "";
	libxml_use_internal_errors(true);
	try
	{
		$STANDINGS_URL = "http://www.cbssports.com/mlb/standings/regular";
		// $WILDCARD_STANDINGS_URL = http://www.cbssports.com/mlb/standings/wildcard
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $STANDINGS_URL);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
		$output = curl_exec($ch);
		$doc = new DOMDocument();
		$doc->loadHTML($output);
		$content = $doc->getElementById('pageRow');
		$tables = $content ->getElementsByTagName('table');
		$count = 0;

		foreach($tables as $table) 
		{
			if ($count !== 0 && $count !== 4)
			{
				$standings_division = Array();
				$rows = $table->getElementsByTagName('tr');
				foreach ($rows as $row) 
				{
					$standings_team = Array();
					$cols = $row->getElementsByTagName('td');
					foreach ($cols as $col) 
					{
						$raw = $col->C14N();
						$rawval = str_replace('<td colspan="15">', '', $raw);
						$rawval = str_replace('<td align="left" width="20%">', '', $rawval);
						$rawval = str_replace('<td align="left">', '', $rawval);
						$rawval = str_replace('<td align="right" width="6%">', '', $rawval);
						$rawval = str_replace('<td align="right" width="5%">', '', $rawval);
						$rawval = str_replace('<td>', '', $rawval);
						$rawval = str_replace('</td>', '', $rawval);
						array_push($standings_team, $rawval);
					}
					array_push($standings_division, $standings_team);
				}
				array_push($standings, $standings_division);
			}
			$count = $count + 1;
			
		}
		$count = 0;

		echo "<table>";
		foreach ($standings as $division) 
		{
			//echo "<tr><td><b>".$division[0][0]."</b></td></tr>\r\n";
			foreach ($division as $team) 
			{
				//echo "<tr><td>".$team[0]."</td></tr>\r\n";
				echo "<tr>\r\n";
				$column = 0;
				foreach($team as $col)
				{
					if ($column!=3 && $column!=5 && $column!=6 && $column!=7 && $column!=8 && $column!=9 && $column!=10 && $column!=11 && $column!=12)
					{
						echo "<td>".$col."</td>";
					}
					
					$column = $column + 1;
				}
				echo "</tr>\r\n";
			}
			$liney = $liney + $linemargin;
			if ($count > 7)
			{
				break;
			}
			$count = $count + 1;
		}
		echo "</table>";
	}
	catch (Exception $e) 
	{
		$lognow = new DateTime();
		$lognow->setTimezone(new DateTimeZone('America/Montreal'));
		$GLOBALS['errors'] = $GLOBALS['errors'] . "<p>".$lognow->format('H:i:s')." - ERROR - Unable to get MLB Standings (".$e->getMessage().")</p>";
	}
	return $retval;
}

function GetMLBStandings2()
{
	$standings = Array();
	$imgcount = 1;

	$liney = 20;
	$lines = array();
		
	$retval = "";
	libxml_use_internal_errors(true);
	try
	{
		$STANDINGS_URL = "http://www.cbssports.com/mlb/standings/regular";
		// $WILDCARD_STANDINGS_URL = http://www.cbssports.com/mlb/standings/wildcard
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $STANDINGS_URL);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
		$output = curl_exec($ch);
		$doc = new DOMDocument();
		$doc->loadHTML($output);
		$content = $doc->getElementById('pageRow');
		$tables = $content ->getElementsByTagName('table');
		$count = 0;

		foreach($tables as $table) 
		{
			if ($count !== 0 && $count !== 4)
			{
				$standings_division = Array();
				$rows = $table->getElementsByTagName('tr');
				foreach ($rows as $row) 
				{
					$standings_team = Array();
					$cols = $row->getElementsByTagName('td');
					foreach ($cols as $col) 
					{
						$raw = $col->C14N();
						$rawval = str_replace('<td colspan="15">', '', $raw);
						$rawval = str_replace('<td align="left" width="20%">', '', $rawval);
						$rawval = str_replace('<td align="left">', '', $rawval);
						$rawval = str_replace('<td align="right" width="6%">', '', $rawval);
						$rawval = str_replace('<td align="right" width="5%">', '', $rawval);
						$rawval = str_replace('<td>', '', $rawval);
						$rawval = str_replace('</td>', '', $rawval);
						array_push($standings_team, $rawval);
					}
					array_push($standings_division, $standings_team);
				}
				array_push($standings, $standings_division);
			}
			$count = $count + 1;
			
		}
		$count = 0;

		echo "<table>";
		foreach ($standings as $division) 
		{
			foreach ($division as $team) 
			{
				echo "<tr>\r\n";
				//echo "<td>TESTIGO</td>";
				$column = 0;
				foreach($team as $col)
				{
				//	if ($column!=3 && $column!=5 && $column!=6 && $column!=7 && $column!=8 && $column!=9 && $column!=10 && $column!=11 && $column!=12)
				//	{
				//		echo "<td>".$col."</td>";
				//	}
					if ($column != 12)
					{
						echo "<td>".$col."</td>";
					}
					$column = $column + 1;
				}
				echo "</tr>\r\n";
			}
			$liney = $liney + $linemargin;
			if ($count > 7)
			{
				break;
			}
			$count = $count + 1;
		}
		echo "</table>";
	}
	catch (Exception $e) 
	{
		$lognow = new DateTime();
		$lognow->setTimezone(new DateTimeZone('America/Montreal'));
		$GLOBALS['errors'] = $GLOBALS['errors'] . "<p>".$lognow->format('H:i:s')." - ERROR - Unable to get MLB Standings (".$e->getMessage().")</p>";
	}
	return $retval;
}



function GetSpecificStatsData($URL, $COLNUM)
{
	$STATS_URL = $URL.$COLNUM;
	$stats = Array();
	$selectedcol = 5;
	$retval = "";
	libxml_use_internal_errors(true);
	try
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $STATS_URL);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
		$output = curl_exec($ch);
		$doc = new DOMDocument();
		$doc->loadHTML($output);
		$rows = $doc->getElementsByTagName('tr');
		foreach($rows as $row) 
		{
			$player_stats = Array();
			$cols = $row->getElementsByTagName('td');
			foreach ($cols as $col) 
			{

				$raw = $col->C14N();
				$rawval = str_replace('<td align="left">', '', $raw);
				$rawval = str_replace('<td align="center">', '', $rawval);
				$rawval = str_replace('<td align="right">', '', $rawval);
				$rawval = str_replace('<td align="right" width="6%">', '', $rawval);
				$rawval = str_replace('<td align="right" width="5%">', '', $rawval);
				$rawval = str_replace('</a>', '', $rawval);
				$rawval = str_replace('<td>', '', $rawval);
				$rawval = str_replace('</td>', '', $rawval);
				$pos = stripos($rawval,">");
				$desc = substr($rawval,$pos+1);
				array_push($player_stats, $desc);
			}
			array_push($stats, $player_stats);
		}
		return $stats;
	}
	catch (Exception $e) 
	{
		$lognow = new DateTime();
		$lognow->setTimezone(new DateTimeZone('America/Montreal'));
		$GLOBALS['errors'] = $GLOBALS['errors'] . "<p>".$lognow->format('H:i:s')." - ERROR - Unable to get MLB Stats (".$e->getMessage().")</p>";
	}
}

function GetSpecificStats($LEAGUE, $COLNUM)
{
	$URL = "http://www.cbssports.com/mlb/stats/playersort/sortableTable/".$LEAGUE."/year-2016-season-regularseason-category-batting-qualifying-1?:sort_col=";
	$retval = "";
	try
	{
		$stats = GetSpecificStatsData($URL, $COLNUM);
		return $stats;
	}
	catch (Exception $e) 
	{
		$lognow = new DateTime();
		$lognow->setTimezone(new DateTimeZone('America/Montreal'));
		$GLOBALS['errors'] = $GLOBALS['errors'] . "<p>".$lognow->format('H:i:s')." - ERROR - Unable to get MLB Stats (".$e->getMessage().")</p>";
	}
}

function GetSpecificPitchingStats($LEAGUE, $COLNUM)
{
	$URL = "http://www.cbssports.com/mlb/stats/playersort/sortableTable/".$LEAGUE."/year-2016-season-regularseason-category-pitching-qualifying-1?:sort_col=";
	$retval = "";
	try
	{
		$stats = GetSpecificStatsData($URL, $COLNUM);
		return $stats;
	}
	catch (Exception $e) 
	{
		$lognow = new DateTime();
		$lognow->setTimezone(new DateTimeZone('America/Montreal'));
		$GLOBALS['errors'] = $GLOBALS['errors'] . "<p>".$lognow->format('H:i:s')." - ERROR - Unable to get MLB Stats (".$e->getMessage().")</p>";
	}
}

function FormatStats($stats, $COLNUM)
{
	$count = 0;
	echo "<tr><td><b>".$HEADER."</b></td></tr>";
	foreach ($stats as $stat) 
	{
		if ($count > 0)
		{
			echo "<tr>\r\n";
			$idx = 0;
			foreach($stat as $col)
			{
				if ($idx == 0 || $idx == 2 || $idx == ($COLNUM-1))
				{
					echo "<td>".$col."</td>";
				}
				$idx = $idx + 1;
			}
			echo "</tr>\r\n";
		}
		if ($count > 7)
		{
			break;
		}
		$count = $count + 1;
	}
	echo "<tr><td>&nbsp;</td></tr>\r\n";
}

function FormatDoubleStats($HEADER, $stats1, $stats2, $COLNUM)
{
	$count = 0;
	echo "<tr><td colspan=7><b>".$HEADER."</b></td></tr>";
	foreach ($stats1 as $stat) 
	{
		if ($count > 0)
		{
			echo "<tr>\r\n";
			$idx = 0;
			foreach($stat as $col)
			{
				if ($idx == 0 || $idx == 2 || $idx == ($COLNUM-1))
				{
					echo "<td>".$col."</td>";
				}
				$idx = $idx + 1;
			}
			$idx = 0;
			//echo "<td>&nbsp;&nbsp;</td>";
			foreach($stats2[$count] as $col)
			{
				if ($idx == 0 || $idx == 2 || $idx == ($COLNUM-1))
				{
					echo "<td>".$col."</td>";
				}
				$idx = $idx + 1;
			}
			echo "</tr>\r\n";
		}
		if ($count > 7)
		{
			break;
		}
		$count = $count + 1;
	}
	echo "<tr><td colspan=7>&nbsp;</td></tr>\r\n";
}

function GetTableStats($statsname,$colnum)
{
	$alstats = GetSpecificStats("al", $colnum);
	$nlstats = GetSpecificStats("nl", $colnum);
	FormatDoubleStats($statsname, $alstats, $nlstats, $colnum);
}

function GetPitchingTableStats($statsname,$colnum)
{
	$alstats = GetSpecificPitchingStats("al", $colnum);
	$nlstats = GetSpecificPitchingStats("nl", $colnum);
	FormatDoubleStats($statsname, $alstats, $nlstats, $colnum);
}

// GET MLB STATS
function GetMLBStats()
{
	echo "<table>";
	GetTableStats("Homeruns", 10);
	GetTableStats("Hits", 7);
	GetTableStats("RBI", 11);
	GetTableStats("OBP", 16);
	GetTableStats("SLG", 17);
	GetTableStats("OPS", 18);
	
	GetPitchingTableStats("W", 7);
	GetPitchingTableStats("ERA", 15);
	GetPitchingTableStats("K", 17);
	GetPitchingTableStats("WHIP", 19);
	echo "</table>";
}

// GET MLB SCORES Tables
function GetMLBScoresTables()
{
	$retval = "";
	libxml_use_internal_errors(true);
	try
	{	
		$date_score = new DateTime();
		if (date('H') < 11) 
		{
			$date_score->modify('-1 day');
		}
		$MLB_ONLINE_BASE_URL = "http://gd2.mlb.com/components/game/mlb/year_";
		$Scores_URL = $MLB_ONLINE_BASE_URL.$date_score->format('Y');
		$Scores_URL = $Scores_URL."/month_".$date_score->format('m');
		$Scores_URL = $Scores_URL."/day_".$date_score->format('d');
		$Scores_URL = $Scores_URL."/master_scoreboard.json";
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $Scores_URL);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
		$output = curl_exec($ch);
		
		$parsed_json = json_decode($output);
		$date_jour = $parsed_json->{'data'}->{'games'}->{'month'};
		$games = $parsed_json->{'data'}->{'games'}->{'game'};

		
		echo "<table>";
		foreach($games as $game) 
		{

			$lines = array();
		
			$awaystr = "<b>".$game->{'away_team_city'}."</b> (".$game->{'away_win'}."-".$game->{'away_loss'}.")";
			$homestr = "<b>".$game->{'home_team_city'}."</b> (".$game->{'home_win'}."-".$game->{'home_loss'}.")";
			
			$awayscore = $game->{'linescore'}->{'r'}->{'away'};
			$homescore = $game->{'linescore'}->{'r'}->{'home'};
			
			$status = $game->{'status'}->{'ind'};
			$statusSTR = $status;
			if ($status == "S" || $status == "P")
			{
				$statusSTR = $game->{'time'};
				$awaypitcher = $game->{'away_probable_pitcher'};
				$homepitcher = $game->{'home_probable_pitcher'};
				array_push($lines, $game->{'away_name_abbrev'}.": ".$awaypitcher->{'first'}." ".$awaypitcher->{'last'}." (".$awaypitcher->{'wins'}."-".$awaypitcher->{'losses'}.", ".$awaypitcher->{'era'}.")");
				array_push($lines, $game->{'home_name_abbrev'}.": ".$homepitcher->{'first'}." ".$homepitcher->{'last'}." (".$homepitcher->{'wins'}."-".$homepitcher->{'losses'}.", ".$homepitcher->{'era'}.")");
				array_push($lines, $game->{'venue'}.", ".$game->{'location'});
			}
			if ($status == "PW")
			{
				$statusSTR = "Warmup";
				$awaypitcher = $game->{'away_probable_pitcher'};
				$homepitcher = $game->{'home_probable_pitcher'};
				array_push($lines, $game->{'away_name_abbrev'}.": ".$awaypitcher->{'first'}." ".$awaypitcher->{'last'}." (".$awaypitcher->{'wins'}."-".$awaypitcher->{'losses'}.", ".$awaypitcher->{'era'}.")");
				array_push($lines, $game->{'home_name_abbrev'}.": ".$homepitcher->{'first'}." ".$homepitcher->{'last'}." (".$homepitcher->{'wins'}."-".$homepitcher->{'losses'}.", ".$homepitcher->{'era'}.")");
				array_push($lines, $game->{'venue'}.", ".$game->{'location'});
			}
			if ($status == "I")
			{
				$statusSTR = "BOT".$game->{'status'}->{'inning'};
				if ($game->{'status'}->{'top_inning'} == "Y")
				{
					$statusSTR = "TOP".$game->{'status'}->{'inning'};
				}
				$pitcher = $game->{'pitcher'};
				$batter = $game->{'batter'};
				$outs = $game->{'status'}->{'o'};
				$outsline = $outs." outs";
				if ($outs == "0")
				{
					$outsline = "No outs";
				}
				else if ($outs == "1")
				{
					$outsline = "One out";
				}
				$runners = $game->{'runners_on_base'}->{'status'};
				$runnersStr = "Nobody on base. ";
				if ($runners !== "0")
				{
					$runner1b = $game->{'runners_on_base'}->{'runner_on_1b'};
					$runner2b = $game->{'runners_on_base'}->{'runner_on_2b'};
					$runner3b = $game->{'runners_on_base'}->{'runner_on_3b'};
					$runnersStr = "";
					if (is_null($runner1b)==False && $runner1b->{'last'}!=="")
					{
						$runnersStr = $runner1b->{'last'}." on first. ";
					}
					if (is_null($runner2b)==False && $runner2b->{'last'}!=="")
					{
						$runnersStr = $runnersStr.$runner2b->{'last'}." on second. ";
					}
					if (is_null($runner3b)==False && $runner3b->{'last'}!=="")
					{
						$runnersStr = $runnersStr = $runnersStr.$runner3b->{'last'}." on third. ";
					}
				}
				
				$current = $runnersStr.$outsline;
				$atbat = "Batter: ". $batter->{'first'}." ".$batter->{'last'}." (".$batter->{'h'}."/".$batter->{'ab'}.", ".$batter->{'avg'}.")";
				$pitching = "Pitching: ". $pitcher->{'first'}." ".$pitcher->{'last'}. " (".$pitcher->{'ip'}." IP, ".$pitcher->{'er'}." ER, ".$pitcher->{'era'}.")";
				array_push($lines, $current);
				array_push($lines, $atbat);
				array_push($lines, $pitching);
			}
			
			echo "<tr>";
			echo "<td>".$awaystr."</td>";
			echo "<td>".$game->{'linescore'}->{'r'}->{'away'}."</td>";
			echo "<td>".$game->{'linescore'}->{'h'}->{'away'}."</td>";
			echo "<td>".$game->{'linescore'}->{'e'}->{'away'}."</td>";
			echo "<td>".$statusSTR."</td>";
			echo "</tr>";
			
			echo "<tr>";
			echo "<td>".$homestr."</td>";
			echo "<td>".$game->{'linescore'}->{'r'}->{'home'}."</td>";
			echo "<td>".$game->{'linescore'}->{'h'}->{'home'}."</td>";
			echo "<td>".$game->{'linescore'}->{'e'}->{'home'}."</td>";
			echo "<td>&nbsp;</td>";
			echo "</tr>";
		

			if ($status=="F")
			{
				$line3 = "W: ".$game->{'winning_pitcher'}->{'first'}." ";
				$line3 = $line3.$game->{'winning_pitcher'}->{'last'}." (";
				$line3 = $line3.$game->{'winning_pitcher'}->{'wins'}."-";
				$line3 = $line3.$game->{'winning_pitcher'}->{'losses'}.", ";
				$line3 = $line3.$game->{'winning_pitcher'}->{'era'}.")";
				
				$line4 = "L: ".$game->{'losing_pitcher'}->{'first'}." ";
				$line4 = $line4.$game->{'losing_pitcher'}->{'last'}." (";
				$line4 = $line4.$game->{'losing_pitcher'}->{'wins'}."-";
				$line4 = $line4.$game->{'losing_pitcher'}->{'losses'}.", ";
				$line4 = $line4.$game->{'losing_pitcher'}->{'era'}.")";
				array_push($lines, $line3);
				array_push($lines, $line4);
				if ($game->{'save_pitcher'}->{'first'}!=="")
				{
					$line5 = "S: ".$game->{'save_pitcher'}->{'first'}." ";
					$line5 = $line5.$game->{'save_pitcher'}->{'last'}." (";
					$line5 = $line5.$game->{'save_pitcher'}->{'saves'}.", ";
					$line5 = $line5.$game->{'save_pitcher'}->{'era'}.")";
					array_push($lines, $line5);
				}
			}
			
			// HOME RUNS
			if ($status !== "S" && $status !== "P" && $status !== "PW")
			{
				$line6 = "HR: ";
				$first = "0";
				$homeruns = $game->{'home_runs'};
				if (is_null($homeruns) ==  False)
				{
					$players = $homeruns->{'player'};
					if (is_array($players) == True)
					{
						foreach ($players as $hr) 
						{
							if ($first == "0")
							{
								$first = "1";
							}
							else
							{
								$line6 = $line6 . ", ";
							}
							$line6 = $line6 . $hr->{'name_display_roster'}. " (".$hr->{'std_hr'}.")";
						}
					}
					else
					{
						$line6 = $line6 . $players->{'name_display_roster'}. " (".$players->{'std_hr'}.")";
					}
				}


				array_push($lines, $line6);
			}
			
			foreach ($lines as $value) 
			{
				$liney = $liney + $linemargin;
				echo "<tr>";
				echo "<td colspan=5>".$value."</td>";
				echo "</tr>";
			}
					
			$imgcount = $imgcount + 1;
			echo "<tr><td colspan=5>&nbsp;</td></tr>";
		}
		echo "</table>";
	}
	catch (Exception $e) 
	{
		$lognow = new DateTime();
		$lognow->setTimezone(new DateTimeZone('America/Montreal'));
		$GLOBALS['errors'] = $GLOBALS['errors'] . "<p>".$lognow->format('H:i:s')." - ERROR - Unable to get MLB Scores (".$e->getMessage().")</p>";
	}
	return $retval;
}

?>